//@ts-nocheck
import { createApp, ComponentPublicInstance, mergeProps } from 'vue'
import Modal, { prefixCls } from './Modal'

export const destroyFns = []

export default function (config) {
  const div = document.createElement('div')
  document.body.appendChild(div)
  config = { ...config, visible: true }

  let ins: ComponentPublicInstance = null

  ins = createApp({
    data: () => ({
      config: { ...config },
      displayed: true
    }),
    render() {
      if (!this.displayed) return
      const config = mergeProps(this.config, { onAfterLeave })
      return (
        <Modal
          {...config}
          v-model={[this.config.visible, 'visible']}
          closable={false}
          footer
        >
          { config.content }
        </Modal>
      )
    }
  }).mount(div)

  function onAfterLeave() {
    if (ins && div.parentNode) {
      ins.displayed = false
      ins = null
      div.parentNode.removeChild(div)
    }
  }
  function update(newConfig) {
    if (!ins) return
    Object.assign(ins.config, newConfig)
  }
  function destroy() {
    const i = destroyFns.indexOf(destroy)
    if (~i) destroyFns.splice(i ,1)
    if (!ins) return
    ins.config.visible = false
  }

  destroyFns.push(destroy)

  return {
    destroy,
    update
  }
}